package com.hupu.jrs.ui.gallery

import android.content.Context
import android.database.Cursor
import android.provider.MediaStore
import com.hupu.jrs.bean.Folder
import com.hupu.jrs.bean.Image
import com.hupu.jrs.injector.PerActivity
import rx.Observable
import rx.Subscription
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.io.File
import java.util.*
import javax.inject.Inject

/**
 * Created by sll on 2016/3/9.
 */
@PerActivity
class GalleryPresenter @Inject
constructor(private val mContext: Context) : GalleryContract.Presenter {

    private val IMAGE_PROJECTION = arrayOf(MediaStore.Images.Media.DATA, MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.DATE_ADDED, MediaStore.Images.Media._ID)

    private var mGalleryView: GalleryContract.View? = null
    private var mSubscription: Subscription? = null
    private val folders = ArrayList<Folder>()
    private var hasFolderGened = false

    override fun attachView(view: GalleryContract.View) {
        mGalleryView = view
    }

    override fun detachView() {
        if (mSubscription != null && !mSubscription!!.isUnsubscribed) {
            mSubscription!!.unsubscribe()
        }
        mGalleryView = null
    }

    override fun onImageAndFolderReceive() {
        mSubscription = Observable.create(Observable.OnSubscribe<Cursor> { subscriber ->
            val cursor = MediaStore.Images.Media.query(mContext.contentResolver,
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_PROJECTION, null, null,
                    IMAGE_PROJECTION[2] + " DESC")
            subscriber.onNext(cursor)
        }).subscribeOn(Schedulers.io()).map<List<Image>> { cursor ->
            val images = ArrayList<Image>()
            if (cursor != null && cursor.count > 0) {
                cursor.moveToFirst()
                do {
                    val path = cursor.getString(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[0]))
                    val name = cursor.getString(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[1]))
                    val dateTime = cursor.getLong(cursor.getColumnIndexOrThrow(IMAGE_PROJECTION[2]))
                    val image = Image(path, name, dateTime)
                    images.add(image)
                    if (!hasFolderGened) {
                        // 获取文件夹名称
                        val imageFile = File(path)
                        val folderFile = imageFile.parentFile
                        val folder = Folder()
                        folder.name = folderFile.name
                        folder.path = folderFile.absolutePath
                        folder.cover = image
                        if (!folders.contains(folder)) {
                            val imageList = ArrayList<Image>()
                            imageList.add(image)
                            folder.images = imageList
                            folders.add(folder)
                        } else {
                            // 更新
                            val f = folders[folders.indexOf(folder)]
                            f.images!!.add(image)
                        }
                        hasFolderGened = true
                    }
                } while (cursor.moveToNext())
            }
            images
        }.observeOn(AndroidSchedulers.mainThread()).subscribe { images ->
            mGalleryView!!.renderImages(images as MutableList<Image>)
            mGalleryView!!.renderFolders(folders)
        }
    }
}
